<template>
  <div>
    <p>
      <button class="btn btn-white btn-default btn-round" @click="list()">
        <i class="ace-icon fa fa-refresh"></i>
        刷新
      </button>
    </p>

    <div class="row">
      <div class="col-md-6">
        <textarea id="resource-textarea" class="form-control" v-model="resourceStr" name="resource" rows="20"></textarea>

        <br>
        <button id="save-btn" type="button" class="btn btn-primary" @click="save()">
          保存
        </button>
      </div>
      <div class="col-md-6">
        <ul id="tree" class="ztree"></ul>
      </div>
    </div>
  </div>
</template>

<script>

  export default {
    name: "system-resource",
    data() {
      return {
        resource: {
          id: null,
          name: null,
          page: null,
          request: null,
          parent: null,
        },
        resources: [],
        resourceStr: '',
        tree: {},
      }
    },
    mounted() {
      let _this = this
      _this.list(1)
    },
    methods: {
      /**
       * 获取资源（分页）
       * @param page
       */
      list() {
        let _this = this

        Loading.show()

        _this.$axios.get(process.env.VUE_APP_SERVER + '/system/admin/resource/load-tree').then((resp) => {
          if (resp.data.success) {
            _this.resources = resp.data.content
            //  最后的参数4是缩进的位数
            _this.resourceStr = JSON.stringify(_this.resources, null, 4)

            _this.initTree()  // 初始化树
            Loading.hide()
          } else {
            Loading.hide()
          }
        })
      },

      /**
       * 保存资源
       */
      save() {
        let _this = this

        //  保存校验
        if (Tool.isEmpty(_this.resourceStr)) {
          Toast.warning('资源不能为空!')
          return
        }
        let json = JSON.parse(_this.resourceStr)

        _this.$axios.post(process.env.VUE_APP_SERVER + '/system/admin/resource/save', json).then((resp) => {
          if (resp.data.success) {
            //  关闭模态框
            $("#form-modal").modal('hide')
            //  刷新表格
            _this.list(1)
            Toast.success('保存成功！')
          } else {
            Toast.warning(resp.data.message)
          }
        })
      },

      /**
       * 初始化zTree, 模板在zTree自带的demo里
       */
      initTree() {
        let _this = this
        let setting = {
          check: {
            enable: false
          },
          data: {
            simpleData: {
              idKey: 'id',
              pIdKey: 'parent', // 指明父节点在数据库里的名称, zTree默认叫pId
              rootPId: '',
              // enable: true
            }
          }
        };

        _this.tree = $.fn.zTree.init($("#tree"), setting, _this.resources);

        //  展开所有节点
        _this.tree.expandAll(true)
      },
    }
  }
</script>

<style scoped>

</style>